import cv2
from loguru import logger
import serial
import traceback
import time

from decision_util import DecisionUtil
from vision_utils import *


# {
#     "center": (249, 239), 棋子圆心位置
#     "axes": 15, 棋子半径
#     "type": 1, 棋子颜色 1白X 0黑O
#     "rect": (
#         (217.00003051757812, 212.55001831054688),
#         (70.7073974609375, 70.7073974609375),
#         1.945142149925232,
#     ),
#     "grid": (2, 1), 所在格子位置
#     "area": 0, 所在区域类型 0棋盘内 1下方存储区 2上方存储区 3棋盘外
#     "real": (170.0, 103.91), 实际位置
# },


DEBUG = 1

cap = cv2.VideoCapture("/dev/video20")
cap.set(3, 680)
cap.set(4, 480)


driver = serial.Serial("/dev/ttyS8", 115200, timeout=None)

setloopok(True)


while DEBUG:
    try:
        input("NEXT >>>")

        point_detail, area_rects = get_main_status(cap)
        cv2.waitKey(1)

        # continue

        posi = point_detail[0]["real"]
        message = f"X{posi[0]},Y{posi[1]}E"
        logger.info(f"Sending {message}")
        driver.write(message.encode("ascii"))

        input("BACK >>>")
        logger.info("Back")
        driver.write("R".encode("ascii"))

    except:
        logger.error(traceback.format_exc())
